//
//  BHStadiumProductDetailViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/2.
//

import UIKit

class BHStadiumProductDetailViewController: BHBaseViewController {

    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-BHCoachInfoBottomView.viewHeight)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    lazy var headerInfoView: BHCoachInfoHeaderView = {
        let view = BHCoachInfoHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHCoachInfoHeaderView.viewHeight)
        return view
    }()
    
    lazy var bottomView: BHCoachInfoBottomView = {
        let view = BHCoachInfoBottomView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.height-BHCoachInfoBottomView.viewHeight, width: UIScreen.width, height: BHCoachInfoBottomView.viewHeight)
        return view
    }()
    
    lazy var payBottomView: BHApplyPayBottomSheetView = {
        let view = BHApplyPayBottomSheetView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
        view.delegate = self
        return view
    }()

    lazy var webCell: BHHtmlContentWebCell = { [weak self] in
        let cell = self?.tableView.dequeueReusableCell(withIdentifier: "BHHtmlContentWebCell", for: IndexPath.init(row: 0, section: 0)) as! BHHtmlContentWebCell
        return cell
    }()
    
    var productId: String = ""
    fileprivate var orderText: String = ""
    fileprivate var proDetailModel = BHGoodDetailModel.init()
    fileprivate var detailIntroduceHeight: CGFloat = 0
    fileprivate var introduceFlag: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "详情"
        self.view.addSubview(self.tableView)
        self.regisetCell()
        self.tableView.tableHeaderView = self.headerInfoView
        self.view.addSubview(self.bottomView)
        self.view.addSubview(self.payBottomView)

        self.loadProductDetailService()
        
        // 购买
        self.bottomView.buy_btn.addBtnAction(action: {[weak self] (_) in
            if self?.proDetailModel.price.isEmpty == true ||
                self?.proDetailModel.price == "0" ||
                self?.proDetailModel.price == "0.0" ||
                self?.proDetailModel.price == "0.00"{
                BHToast.toast(text: "无需支付")
                return
            }
            
            self?.createOrderService()
        }, for: .touchUpInside)
        
        self.bottomView.ask_view.addViewAction {[weak self] (_) in
            if self?.proDetailModel.contactNumber.isEmpty == true {
                BHToast.toast(text: "当无联系方式")
                return
            }
            
            BHCommonTool.telAct(self?.proDetailModel.contactNumber ?? "") { (open) in
                if open == false {
                    BHToast.toast(text: "当前设备暂时无法拨打电话")
                }
            }
        }
        
        self.webCell.webCellCallRealHeightBlock = { [weak self] height in
            self?.detailIntroduceHeight = height
            self?.tableView.reloadData()
        }
    }
    
    private func regisetCell()  {
        self.tableView.regiseterNib(nibName: "BHCoachRefundDescriptionCell")
        self.tableView.register(BHHtmlContentWebCell.self, forCellReuseIdentifier: "BHHtmlContentWebCell")
    }
    
}

extension BHStadiumProductDetailViewController: BHApplyPayBottomSheetViewDelegate {
    func goPayAct() {
        self.goAlipayAct()
    }
}
extension BHStadiumProductDetailViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if self.proDetailModel.introduce.isEmpty == true {
                return 0
            }else {
                if self.introduceFlag == false {
                    if self.detailIntroduceHeight > 150 {
                        return 150
                    }
                }
                return self.detailIntroduceHeight
            }
        }else if (indexPath.section == 1) {
            return 45
        }
       return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return CGFloat.leastNormalMagnitude
        }
        return 55
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            if self.detailIntroduceHeight > 150 {
                return BHStadiumShowMoreFooter.moreHeight
            }
        }
        return CGFloat.leastNormalMagnitude
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            if self.detailIntroduceHeight > 150 {
                let view = BHStadiumShowMoreFooter.loadFromXib()
                view.showMoreBtn.isSelected = self.introduceFlag
                view.showMoreBtn.addBtnAction(action: {[weak self] (_) in
                    self?.introduceFlag = !(self?.introduceFlag ?? false)
                    
                    tableView.reloadData()
                }, for: .touchUpInside)
                return view
            }
        }
        return nil
    }
}

extension BHStadiumProductDetailViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            let view  = BHStadiumSecHeaderView.loadFromXib()
            view.moreBtn.isHidden = true
            view.name_label.text = "详情"
            return view
        }else {
            return nil
        }
    }

 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            return self.webCell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "BHCoachRefundDescriptionCell", for: indexPath) as! BHCoachRefundDescriptionCell
            cell.rule_btn.setTitle("\(self.proDetailModel.backRule) ", for: .normal)
            return cell
        }
    }
}

// MARK: 获取商品详情
extension BHStadiumProductDetailViewController {
    func loadProductDetailService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.stadium_detail_product_detailUrl, paramters: ["id":self.productId]) { (success, errorMsg, responseDic) in
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let model = BHGoodDetailModel.init()
                model.parseDic(result)
                
                self.proDetailModel = model
                self.tableView.reloadData()
                
                self.webCell.htmlText = model.introduce
                self.headerInfoView.proDetailModel = model
                self.bottomView.price_label.text = model.price
                self.payBottomView.price = model.price
            }else {
                BHToast.toast(text: errorMsg)
            }
            SVProgressHUD.dismiss()
        }
    }
    
    
    // 下单
    func createOrderService()  {
        SVProgressHUD.show()
        BHCommonService.createOrder(type: 1, businessId: self.productId, payType: 1) { (success, text) in
            SVProgressHUD.dismiss()
            if success == true {
                self.orderText = text
                self.payBottomView.show()
            }else {
                BHToast.toast(text: text)
            }
        }
    }
    
    // 去支付
    func goAlipayAct()  {
        BHPayManager.init().begainBuy(orderText: self.orderText) { (success, errorMsg) in
            BHToast.toast(text: errorMsg)
            if success == true {
                BHToast.toast(text: "支付成功")
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
